<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<script>
require([
    "jquery",
    "uiRegistry",
    "Magento_Ui/js/modal/alert",
    'Magento_Ui/js/modal/prompt',
    "collapsable",
    "prototype"
], function (jQuery, rg, alert, prompt) {
    var frontendInput = $('frontend_input');

    function toggleApplyVisibility (select) {
        if ($(select).value == 1) {
            $(select).next('select').removeClassName('no-display');
            $(select).next('select').removeClassName('ignore-validate');

        } else {
            $(select).next('select').addClassName('no-display');
            $(select).next('select').addClassName('ignore-validate');
            var options = $(select).next('select').options;
            for( var i=0; i < options.length; i++) {
                options[i].selected = false;
            }
        }
    }
    function getFrontTab () {
        var tabsFront = $('product_attribute_tabs_front');
        if (tabsFront) {
            return tabsFront.up('li');
        } else {
            return $('front_fieldset-wrapper');
        }
    }

    function checkOptionsPanelVisibility () {
        var optionsPanel = $('manage-options-panel'),
            visualOptionsPanel = $('swatch-visual-options-panel'),
            textOptionsPanel = $('swatch-text-options-panel');
        if (optionsPanel) {
            var panel = optionsPanel.up('.fieldset');

            if (frontendInput && (frontendInput.value=='select' || frontendInput.value=='multiselect')) {
                panel.show();
                rg.get('manage-options-panel', function () {
                    jQuery('#manage-options-panel').trigger('render');
                });
            } else {
                panel.hide();
            }
        }
        if (visualOptionsPanel) {
            var visualPanel = visualOptionsPanel.up('.fieldset');

            if (frontendInput && frontendInput.value=='swatch_visual') {
                visualPanel.show();
                rg.get('swatch-visual-options-panel', function () {
                    jQuery('#swatch-visual-options-panel').trigger('render');
                });
            } else {
                visualPanel.hide();
            }
        }
        if (textOptionsPanel) {
            var textPanel = textOptionsPanel.up('.fieldset');

            if (frontendInput && frontendInput.value=='swatch_text') {
                textPanel.show();
                rg.get('swatch-text-options-panel', function () {
                    jQuery('#swatch-text-options-panel').trigger('render');
                });
            } else {
                textPanel.hide();
            }
        }
    }

    function bindAttributeInputType () {
        var isFilterable = $('is_filterable'),
            isFilterableInSearch = $('is_filterable_in_search'),
            backendType = $('backend_type'),
            usedForSortBy = $('used_for_sort_by'),
            frontendClass = $('frontend_class'),
            selectFields = ['select', 'multiselect', 'price', 'swatch_text', 'swatch_visual'];

        checkOptionsPanelVisibility();
        switchDefaultValueField();
        if (frontendInput
            && jQuery.inArray(frontendInput.value, selectFields) >= 0
        ) {
            if (isFilterable && !isFilterable.getAttribute('readonly')) {
                isFilterable.disabled = false;
            }
            if (isFilterableInSearch && !isFilterableInSearch.getAttribute('readonly')) {
                isFilterableInSearch.disabled = false;
            }
            if (backendType && backendType.options) {
                for (var i=0; i<backendType.options.length; i++) {
                    if (backendType.options[i].value=='int') {
                        backendType.selectedIndex = i;
                    }
                }
            }
        } else {
            if (isFilterable) {
                isFilterable.selectedIndex=0;
                isFilterable.disabled = true;
            }
            if (isFilterableInSearch) {
                isFilterableInSearch.disabled = true;
            }
        }

        if (frontendInput && (frontendInput.value=='multiselect'
            || frontendInput.value=='gallery'
            || frontendInput.value=='textarea')) {
            if (usedForSortBy) {
                usedForSortBy.disabled = true;
            }
        } else {
            if (usedForSortBy && !usedForSortBy.getAttribute('readonly')) {
                usedForSortBy.disabled = false;
            }
        }

        if (jQuery('#frontend_input').val() == 'swatch_text') {
            jQuery('.swatch-text-field-0').addClass('required-option');
        } else {
            jQuery('.swatch-text-field-0').removeClass('required-option');
        }

        setRowVisibility('is_wysiwyg_enabled', false);
        setRowVisibility('is_html_allowed_on_front', false);

        switch (frontendInput.value) {
            case 'textarea':
                setRowVisibility('is_wysiwyg_enabled', true);
                if ($('is_wysiwyg_enabled').value == '0') {
                    setRowVisibility('is_html_allowed_on_front', true);
                    $('is_html_allowed_on_front').disabled = false;
                }
                frontendClass.value = '';
                frontendClass.disabled = true;
                break;
            case 'text':
                setRowVisibility('is_html_allowed_on_front', true);
                $('is_html_allowed_on_front').disabled = false;

                if (!frontendClass.getAttribute('readonly')) {
                    frontendClass.disabled = false;
                }
                break;
            case 'select':
            case 'multiselect':
                setRowVisibility('is_html_allowed_on_front', true);
                $('is_html_allowed_on_front').disabled = false;
                frontendClass.value = '';
                frontendClass.disabled = true;
                break;
            default:
                frontendClass.value = '';
                frontendClass.disabled = true;
        }

        switchIsFilterable();
    }

    function switchIsFilterable () {
        var isFilterable = $('is_filterable'),
            position = $('position');
        if (isFilterable) {
            if (isFilterable.selectedIndex == 0) {
                position.disabled = true;
            } else {
                if (!position.getAttribute('readonly')) {
                    position.disabled = false;
                }
            }
        }
    }

    function switchDefaultValueField () {
        if (!frontendInput) {
            return;
        }

        var currentValue = frontendInput.value;

        var defaultValueTextVisibility = false;
        var defaultValueTextareaVisibility = false;
        var defaultValueDateVisibility = false;
        var defaultValueYesnoVisibility = false;
        var scopeVisibility = true;

        /* swatch attributes */
        var useProductImageForSwatch = false;
        var defaultValueUpdateImage = false;

        var optionDefaultInputType = '';


        switch (currentValue) {
            case 'select':
                optionDefaultInputType = 'radio';
                break;

            case 'multiselect':
                optionDefaultInputType = 'checkbox';
                break;

            case 'date':
                defaultValueDateVisibility = true;
                break;

            case 'boolean':
                defaultValueYesnoVisibility = true;
                break;

            case 'textarea':
                defaultValueTextareaVisibility = true;
                break;

            case 'media_image':
                defaultValueTextVisibility = false;
                break;
            case 'price':
                scopeVisibility = false;
                break;
            case 'swatch_visual':
                useProductImageForSwatch = true;
                defaultValueUpdateImage = true;
                defaultValueTextVisibility = false;
                break;
            case 'swatch_text':
                useProductImageForSwatch = false;
                defaultValueUpdateImage = true;
                defaultValueTextVisibility = false;
                break;
            default:
                defaultValueTextVisibility = true;
                break;
        }

        switch (currentValue) {
            case 'media_image':
                getFrontTab().hide();

                setRowVisibility('is_required', false);
                setRowVisibility('is_unique', false);
                setRowVisibility('frontend_class', false);
            break;
        <?php $hiddenFields = $this->helper('Magento\Catalog\Helper\Data')->getAttributeHiddenFields() ?>
        <?php foreach ($hiddenFields as $type => $fields): ?>
        <?php if (in_array($type, array('swatch_visual', 'swatch_text'))) continue ?>
            case '<?php echo $block->escapeHtml($type); ?>':
                <?php foreach ($fields as $one): ?>
                    <?php if ($one == '_front_fieldset'): ?>
                        getFrontTab().hide();
                    <?php elseif ($one == '_default_value'): ?>
                        defaultValueTextVisibility =
                        defaultValueTextareaVisibility =
                        defaultValueDateVisibility =
                        defaultValueYesnoVisibility = false;
                    <?php elseif ($one == '_scope'): ?>
                        scopeVisibility = false;
                    <?php else: ?>
                        setRowVisibility('<?php echo $block->escapeHtml($one); ?>', false);
                    <?php endif; ?>
                <?php endforeach; ?>
            break;
        <?php endforeach; ?>

            default:
                getFrontTab().show();

                showDefaultRows();
            break;
        }

        setRowVisibility('default_value_text', defaultValueTextVisibility);
        setRowVisibility('default_value_textarea', defaultValueTextareaVisibility);
        setRowVisibility('default_value_date', defaultValueDateVisibility);
        setRowVisibility('default_value_yesno', defaultValueYesnoVisibility);
        setRowVisibility('is_global', scopeVisibility);

        /* swatch attributes */
        setRowVisibility('use_product_image_for_swatch', useProductImageForSwatch);
        setRowVisibility('update_product_preview_image', defaultValueUpdateImage);

        var elems = document.getElementsByName('default[]');
        for (var i = 0; i < elems.length; i++) {
            elems[i].type = optionDefaultInputType;
        }
    }

    function showDefaultRows () {
        setRowVisibility('is_required', true);
        setRowVisibility('is_unique', true);
        setRowVisibility('frontend_class', true);
    }

    function setRowVisibility (id, isVisible) {
        if ($(id)) {
            var td = $(id).parentNode;
            var tr = $(td.parentNode);

            if (isVisible) {
                tr.show();
            } else {
                tr.blur();
                tr.hide();
            }
        }
    }


    function updateRequriedOptions () {
        if ($F('frontend_input')=='select' && $F('is_required')==1) {
            $('option-count-check').addClassName('required-options-count');
        } else {
            $('option-count-check').removeClassName('required-options-count');
        }
    }

    function saveAttributeInNewSet (promptMessage) {
        var newAttributeSetName;

        prompt({
            content: promptMessage,
            actions: {
                confirm: function (val) {
                    newAttributeSetName = val;

                    if (!newAttributeSetName) {
                        return;
                    }

                    var rules = ['required-entry', 'validate-no-html-tags'];
                    for (var i = 0; i < rules.length; i++) {
                        if (!jQuery.validator.methods[rules[i]](newAttributeSetName)) {
                            alert({
                                content: jQuery.validator.messages[rules[i]]
                            });

                            return;
                        }
                    }

                    var newAttributeSetNameInputId = 'new_attribute_set_name';

                    if ($(newAttributeSetNameInputId)) {
                        $(newAttributeSetNameInputId).value = newAttributeSetName;
                    } else {
                        $('edit_form').insert({
                            top: new Element('input', {
                                type: 'hidden',
                                id: newAttributeSetNameInputId,
                                name: 'new_attribute_set_name',
                                value: newAttributeSetName
                            })
                        });
                    }
                    // Temporary solution will replaced after refactoring of attributes functionality
                    jQuery('#edit_form').triggerHandler('save');
                }
            }
        });
    }

    if (frontendInput) {
        Event.observe(frontendInput, 'change', updateRequriedOptions);
        Event.observe(frontendInput, 'change', bindAttributeInputType);
    }

    if ($('is_filterable')) {
        Event.observe($('is_filterable'), 'change', switchIsFilterable);
    }

    if ($('is_required')) {
        Event.observe($('is_required'), 'change', updateRequriedOptions);
    }

    jQuery(function ($) {
        bindAttributeInputType();
        // @todo: refactor collapsable component
        $('.attribute-popup .collapse, [data-role="advanced_fieldset-content"]')
            .collapsable()
            .collapse('hide');
    });

    window.saveAttributeInNewSet = saveAttributeInNewSet;
    window.updateRequriedOptions = updateRequriedOptions;
    window.setRowVisibility = setRowVisibility;
    window.showDefaultRows = showDefaultRows;
    window.switchDefaultValueField = switchDefaultValueField;
    window.switchIsFilterable = switchIsFilterable;
    window.switchIsFilterable = switchIsFilterable;
    window.bindAttributeInputType = bindAttributeInputType;
    window.checkOptionsPanelVisibility = checkOptionsPanelVisibility;
    window.getFrontTab = getFrontTab;
    window.toggleApplyVisibility = toggleApplyVisibility;

});
</script>
